<template>
  <li
    @mouseenter="mouseHandler(true)"
    @mouseleave="mouseHandler(false)"
    :style="{ backgroundColor: bgColor, color: myColor }"
  >
    <label>
      <input type="checkbox" v-model="isComplete" />
      <span>&nbsp;{{ todo.title }}</span>
    </label>
    <button class="btn btn-danger" v-if="isShow" @click="del">删除</button>
  </li>
</template>
<script lang="ts">
import { computed, defineComponent, ref } from "vue";
import { Todo } from "./../types/Todo";
export default defineComponent({
  name: "Item",
  props: {
    todo: Object as () => Todo, // 函数返回Todo类型
    delTodo: {
      type: Function,
      required: true,
    },
    index: {
      type: Number,
      required: true,
    },
    updateTodo: {
      type: Function,
      required: true,
    },
  },
  setup(props) {
    // 背景色
    const bgColor = ref<string>("white");
    // 字体颜色
    const myColor = ref<string>("black");
    // 删除按钮默认不显示
    const isShow = ref<boolean>(false);
    // 鼠标进入和离开事件回调
    const mouseHandler = (flag: boolean) => {
      if (flag) {
        // 鼠标进入
        bgColor.value = "pink";
        myColor.value = "green";
        isShow.value = true;
      } else {
        // 鼠标离开
        bgColor.value = "white";
        myColor.value = "black";
        isShow.value = false;
      }
    };

    // 删除数据方法
    const del = () => {
      // 提示
      if (window.confirm("确定要删除吗？")) {
        props.delTodo(props.index);
      }
    };

    // 计算属性方式--来让当前的复选框选中/不选中
    const isComplete = computed({
      get() {
        return props.todo.isCompleted;
      },
      set(val) {
        // todo 对象中的isComplete属性操作
        props.updateTodo(props.todo, val);
      },
    });

    return {
      mouseHandler,
      bgColor,
      myColor,
      isShow,
      del,
      isComplete,
    };
  },
});
</script>

<style scoped>
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}
li label {
  float: left;
  cursor: pointer;
}
li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}
li button {
  float: right;
  margin-top: 3px;
}
li::before {
  content: initial;
}
li:last-child {
  border-bottom: none;
}
</style>